#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include "errlib.h"
#include "server_backend.h"

/* set signals handler */
void
setSignalCatcher(void)
{
	signal(SIGINT, exit);
	signal(SIGTERM, exit);
	signal(SIGQUIT, exit);
	signal(SIGALRM, exit);
}

/* create and lock file */
void
lockfile(void)
{
	int fd;	
	struct flock my_lock;

	if ((fd = open(LOCKFILE, O_CREAT | O_RDWR)) == -1)
		fatal("server: another instance is already running");
	
	atexit(unlockfile);

	my_lock.l_type = F_WRLCK;
	my_lock.l_whence = SEEK_SET;
	my_lock.l_start = 0;
	my_lock.l_len = 10;

	if (fcntl(fd, F_SETLKW, &my_lock) == -1)
		fatal("server: lockfile");
}

/* remove lock file */
void
unlockfile(void)
{
	remove(LOCKFILE);
}

/* makes an add operation */
double
add(double op1, double op2)
{
	return op1 + op2;
}

/* makes a substract operation */
double 
sub(double op1, double op2)
{
	return op1 - op2;
}

/* makes a multiplication operation */
double 
mult(double op1, double op2)
{
	return op1 * op2;
}

/* makes a division operation */
double 
divide(double op1, double op2)
{
	if(op2 == 0)
		return 0;	
	return op1 / op2;
}

